const vscode = require('vscode');

/**
 * MCP命令管理器，用于注册与MCP相关的VSCode命令
 */
class McpCommandManager {
    constructor(context, mcpService) {
        this.context = context;
        this.mcpService = mcpService;
        this.disposables = [];
    }

    /**
     * 注册所有MCP相关命令
     */
    register() {
        // 添加MCP服务器命令
        this.registerCommand('mcp.addServer', this.addServer.bind(this));
        
        // 删除MCP服务器命令
        this.registerCommand('mcp.deleteServer', this.deleteServer.bind(this));
        
        // 启用/禁用MCP服务器命令
        this.registerCommand('mcp.toggleServer', this.toggleServer.bind(this));
        
        // 设置工具自动批准命令
        this.registerCommand('mcp.toggleToolAutoApprove', this.toggleToolAutoApprove.bind(this));
        
        // 打开MCP配置命令
        this.registerCommand('mcp.openConfig', this.openConfig.bind(this));
        
        // 显示MCP服务器信息命令
        this.registerCommand('mcp.showServerInfo', this.showServerInfo.bind(this));
        
        console.log('已注册MCP命令');
    }

    /**
     * 清理资源
     */
    dispose() {
        this.disposables.forEach(d => d.dispose());
        this.disposables = [];
    }

    /**
     * 注册VSCode命令
     */
    registerCommand(command, handler) {
        const disposable = vscode.commands.registerCommand(command, handler);
        this.context.subscriptions.push(disposable);
        this.disposables.push(disposable);
    }

    /**
     * 添加MCP服务器
     */
    async addServer() {
        const serverName = await vscode.window.showInputBox({
            prompt: '输入MCP服务器名称',
            placeHolder: '例如: my-mcp-server'
        });

        if (!serverName) {
            return; // 用户取消
        }

        const serverUrl = await vscode.window.showInputBox({
            prompt: '输入MCP服务器URL',
            placeHolder: '例如: http://localhost:3000/mcp'
        });

        if (!serverUrl) {
            return; // 用户取消
        }

        try {
            await this.mcpService.addServer(serverName, serverUrl);
            vscode.window.showInformationMessage(`已添加MCP服务器: ${serverName}`);
        } catch (error) {
            vscode.window.showErrorMessage(`添加MCP服务器失败: ${error instanceof Error ? error.message : String(error)}`);
        }
    }

    /**
     * 删除MCP服务器
     */
    async deleteServer() {
        const servers = this.mcpService.getServers();
        if (servers.length === 0) {
            vscode.window.showInformationMessage('没有可用的MCP服务器');
            return;
        }

        const serverItems = servers.map(server => ({
            label: server.name,
            description: server.disabled ? '(已禁用)' : '(已启用)',
            server
        }));

        const selectedItem = await vscode.window.showQuickPick(serverItems, {
            placeHolder: '选择要删除的MCP服务器'
        });

        if (!selectedItem) {
            return; // 用户取消
        }

        try {
            await this.mcpService.deleteServer(selectedItem.server.name);
            vscode.window.showInformationMessage(`已删除MCP服务器: ${selectedItem.server.name}`);
        } catch (error) {
            vscode.window.showErrorMessage(`删除MCP服务器失败: ${error instanceof Error ? error.message : String(error)}`);
        }
    }

    /**
     * 启用/禁用MCP服务器
     */
    async toggleServer() {
        const servers = this.mcpService.getServers();
        if (servers.length === 0) {
            vscode.window.showInformationMessage('没有可用的MCP服务器');
            return;
        }

        const serverItems = servers.map(server => ({
            label: server.name,
            description: server.disabled ? '(已禁用)' : '(已启用)',
            server
        }));

        const selectedItem = await vscode.window.showQuickPick(serverItems, {
            placeHolder: '选择要切换状态的MCP服务器'
        });

        if (!selectedItem) {
            return; // 用户取消
        }

        try {
            const enabled = !!selectedItem.server.disabled; // 如果当前是禁用状态，则启用；反之亦然
            await this.mcpService.toggleServer(selectedItem.server.name, enabled);
            vscode.window.showInformationMessage(
                `MCP服务器 ${selectedItem.server.name} 已${enabled ? '启用' : '禁用'}`
            );
        } catch (error) {
            vscode.window.showErrorMessage(
                `切换服务器状态失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 切换工具自动批准设置
     */
    async toggleToolAutoApprove() {
        const servers = this.mcpService.getServers().filter(s => !s.disabled);
        if (servers.length === 0) {
            vscode.window.showInformationMessage('没有可用的MCP服务器');
            return;
        }

        const serverItems = servers.map(server => ({
            label: server.name,
            description: `(${server.tools?.length || 0}个工具)`,
            server
        }));

        const selectedServer = await vscode.window.showQuickPick(serverItems, {
            placeHolder: '选择包含工具的MCP服务器'
        });

        if (!selectedServer || !selectedServer.server.tools || selectedServer.server.tools.length === 0) {
            vscode.window.showInformationMessage('所选服务器没有可用工具');
            return;
        }

        const toolItems = selectedServer.server.tools.map(tool => ({
            label: tool.name,
            description: tool.description,
            detail: tool.autoApprove ? '自动批准: 是' : '自动批准: 否',
            picked: tool.autoApprove,
            tool
        }));

        const selectedTools = await vscode.window.showQuickPick(toolItems, {
            placeHolder: '选择要切换自动批准设置的工具',
            canPickMany: true
        });

        if (!selectedTools || selectedTools.length === 0) {
            return; // 用户取消
        }

        const autoApproveOptions = [
            { label: '是', description: '允许工具自动执行，无需确认' },
            { label: '否', description: '工具执行前需要用户确认' }
        ];

        const autoApproveChoice = await vscode.window.showQuickPick(autoApproveOptions, {
            placeHolder: '设置选定工具是否自动批准'
        });

        if (!autoApproveChoice) {
            return; // 用户取消
        }

        try {
            const autoApprove = autoApproveChoice.label === '是';
            const toolNames = selectedTools.map(t => t.tool.name);
            
            await this.mcpService.toggleToolAutoApprove(
                selectedServer.server.name,
                toolNames,
                autoApprove
            );
            
            vscode.window.showInformationMessage(
                `已${autoApprove ? '启用' : '禁用'}自动批准，影响了 ${toolNames.length} 个工具`
            );
        } catch (error) {
            vscode.window.showErrorMessage(
                `更新工具自动批准设置失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 打开MCP配置文件
     */
    async openConfig() {
        try {
            // 获取MCP配置文件路径
            const mcpHub = this.mcpService;
            if (mcpHub && mcpHub.mcpHub) {
                try {
                    const settingsPath = await mcpHub.mcpHub.getMcpSettingsFilePath();
                    // 确保文件存在后再打开
                    const document = await vscode.workspace.openTextDocument(settingsPath);
                    await vscode.window.showTextDocument(document);
                } catch (error) {
                    console.error('获取或打开配置文件失败:', error);
                    vscode.window.showErrorMessage(
                        `无法打开MCP配置文件: ${error instanceof Error ? error.message : String(error)}`
                    );
                }
            } else {
                throw new Error('MCP Hub未初始化');
            }
        } catch (error) {
            vscode.window.showErrorMessage(
                `打开MCP配置失败: ${error instanceof Error ? error.message : String(error)}`
            );
        }
    }

    /**
     * 显示服务器信息
     */
    async showServerInfo() {
        const servers = this.mcpService.getServers();
        if (servers.length === 0) {
            vscode.window.showInformationMessage('没有可用的MCP服务器');
            return;
        }

        const serverItems = servers.map(server => ({
            label: server.name,
            description: server.disabled ? '(已禁用)' : '(已启用)',
            server
        }));

        const selectedItem = await vscode.window.showQuickPick(serverItems, {
            placeHolder: '选择要查看的MCP服务器'
        });

        if (!selectedItem) {
            return; // 用户取消
        }

        const server = selectedItem.server;
        const toolsCount = server.tools?.length || 0;
        
        // 创建服务器信息面板
        const panel = vscode.window.createWebviewPanel(
            'mcpServerInfo',
            `MCP服务器: ${server.name}`,
            vscode.ViewColumn.One,
            { enableScripts: true }
        );

        // 设置HTML内容
        panel.webview.html = `
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>MCP服务器信息</title>
                <style>
                    body { font-family: Arial, sans-serif; padding: 20px; }
                    h1 { color: #333; }
                    .info-item { margin-bottom: 10px; }
                    .label { font-weight: bold; display: inline-block; width: 120px; }
                    .tools-list { margin-top: 20px; }
                    .tool-item { margin-bottom: 10px; padding: 10px; background: #f5f5f5; border-radius: 3px; }
                </style>
            </head>
            <body>
                <h1>${server.name}</h1>
                <div class="info-item">
                    <span class="label">URL:</span>
                    <span>${server.url || '未设置'}</span>
                </div>
                <div class="info-item">
                    <span class="label">状态:</span>
                    <span>${server.disabled ? '已禁用' : '已启用'}</span>
                </div>
                <div class="info-item">
                    <span class="label">超时设置:</span>
                    <span>${server.timeoutSeconds || 30}秒</span>
                </div>
                <div class="info-item">
                    <span class="label">工具数量:</span>
                    <span>${toolsCount}</span>
                </div>
                
                ${toolsCount > 0 ? `
                <div class="tools-list">
                    <h2>可用工具</h2>
                    ${server.tools.map(tool => `
                        <div class="tool-item">
                            <div><strong>${tool.name}</strong></div>
                            ${tool.description ? `<div>${tool.description}</div>` : ''}
                            <div>自动批准: ${tool.autoApprove ? '是' : '否'}</div>
                        </div>
                    `).join('')}
                </div>
                ` : ''}
            </body>
            </html>
        `;
    }
}

module.exports = { McpCommandManager }; 